﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Security;

namespace Core.CMS.ServerControls
{
    public enum SecurityAction
    {
        Hide,
        Disable,
        Redirect,
        ThrowException
    }
    public class SecurityContextExtender : Control
    {
        SecurityAction _action;
        string _target = "";
        string _redirect = "";
        string _role = "";

        public string TargetControlID
        {
            get { return _target; }
            set { _target = value; }
        }

        public string RedirectionUrl
        {
            get { return _redirect; }
            set { _redirect = value; }
        }

        public string RequiredRole
        {
            get { return _role; }
            set { _role = value; }
        }

        public SecurityAction ActionOnFail
        {
            get { return _action; }
            set { _action = value; }
        }

        public SecurityContextExtender()
        {

        }

        protected override void OnLoad(EventArgs e)
        {
            bool passed = SecurityAssert();
            if (!passed)
            {
                switch (_action)
                {
                    case SecurityAction.Disable:
                        Control c = this.Parent.FindControl(TargetControlID);
                        Panel p = new Panel();
                        p.Controls.Add(c);
                        p.Enabled = false;
                        c.Parent.Controls.Add(p);
                        c.Parent.Controls.Remove(c);
                        break;
                    case SecurityAction.Hide:
                        this.Parent.FindControl(TargetControlID).Visible = false;
                        break;
                    case SecurityAction.Redirect:
                        Page.Response.Redirect(RedirectionUrl);
                        break;
                    case SecurityAction.ThrowException:
                        throw new SecurityException("Access denied to component \"" + TargetControlID + "\".");
                }
            }
            base.OnLoad(e);
        }

        private bool SecurityAssert()
        {
            bool passed = false;
 
            if (Page.User.Identity.IsAuthenticated)
            {
                if (Page.User.IsInRole("Administrators") || Page.User.IsInRole(_role))
                    passed = true;
            }

            return passed;
        }
    }
}
